package model

import (
	"fmt"
	"gitee.com/liumou_site/logger"
	"github.com/spf13/cast"
	"io"
	"net/http"
	"net/url"
)

// GetUrlInId 通过id获取URL
func (api *DownLoad) GetUrlInId(id string) (error, string) {
	urls := fmt.Sprintf("%s/post/text/url", api.Http)
	formData := url.Values{}
	formData.Set("key", api.Key)
	formData.Set("id", id)
	if api.Debug {
		logger.Debug("请求参数: ", formData)
		logger.Debug("请求地址: ", urls)
	}

	response, err := http.PostForm(urls, formData)
	if err != nil {
		logger.Error(err.Error())
		return err, ""
	}
	// 读取响应结果
	body, err := io.ReadAll(response.Body)
	if err != nil {
		logger.Error("Failed to read response:", err)
		return err, ""
	}
	// 打印响应结果
	return nil, string(body)
}

// GetUrlTotal 获取URL总数
func (api *DownLoad) GetUrlTotal() (error, int) {
	var urls string
	formData := url.Values{}
	urls = fmt.Sprintf("%s/api/get/total", api.Http)
	if api.Debug {
		logger.Debug("请求参数: ", formData)
		logger.Debug("请求地址: ", urls)
	}
	formData.Set("key", api.Key)
	response, err := http.PostForm(urls, formData)
	if err != nil {
		logger.Error(err.Error())
		return err, 0
	}
	// 读取响应结果
	body, err := io.ReadAll(response.Body)
	if err != nil {
		logger.Error("Failed to read response:", err)
		return err, 0
	}
	logger.Debug("当前数据库总数: ", string(body))
	// 打印响应结果
	return nil, cast.ToInt(string(body))
}
